package org.pms.servlet;

import org.pms.dto.ResultDto;
import org.pms.utils.GsonUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/**
 * 定义一个Servlet -- 用于统一的对 ResultDao进行封装 -- 便于重用
 */
public class BaseServlet extends HttpServlet {

    /**
     * 成功响应数据的封装
     * @param data 响应数据
     * @return
     */
    public ResultDto successJson(Object data) {
        ResultDto resultDto = new ResultDto();
        resultDto.setData(data);
        return resultDto;
    }

    public ResultDto successJson(Object data,String msg) {
        ResultDto resultDto = new ResultDto();
        resultDto.setData(data);
        resultDto.setMsg(msg);
        return resultDto;
    }

    public ResultDto successJson() {
        return new ResultDto();
    }


    /**
     * 错误的响应
     * @return
     */
    public ResultDto errorJson() {
        ResultDto resultDto = new ResultDto();
        resultDto.setCode(500);
        resultDto.setMsg("系统繁忙，请稍后再试!");
        return resultDto;
    }

    public ResultDto errorJson(int code, String msg) {
        ResultDto resultDto = new ResultDto();
        resultDto.setCode(code);
        resultDto.setMsg(msg);
        return resultDto;
    }

    public ResultDto errorJson(String msg) {
        ResultDto resultDto = new ResultDto();
        resultDto.setCode(500);
        resultDto.setMsg(msg);
        return resultDto;
    }


    public Map<String,String> parseMap(HttpServletRequest req) throws IOException {
        // 1.通过DAO获取数据库的数据
        BufferedReader reader = req.getReader();

        String str = null ;
        String jsonParams = "" ;
        // jsonParams = "xx=xx&yy=yy&zz=zz"
        while((str=reader.readLine())!=null) {
            // 把读取的数据，串联起来
            jsonParams = jsonParams + str ;
        }

        return  GsonUtil.toMap(jsonParams) ;

    }
}
